/**
 * Created by forcht on 2018/5/21.
 */
public class Solution {
    public int[][] generateMatrix(int n) {
        int[][] p=new int[n][n];
        int x=0,y=0,i=1;
        int[] dx={0,1,0,-1};
        int[] dy={1,0,-1,0};
        int row=0,column=0;
        while (i<=n*n){
            while (row<n&&row>=0&&column<n&&column>=0&&p[row][column]==0){
                p[row][column]=i++;
                row+=dx[x];
                column+=dy[y];
            }
            row-=dx[x];
            column-=dy[y];
            x=(x+1)%4;
            y=(y+1)%4;
            row+=dx[x];
            column+=dy[y];
        }
        return p;
    }

    public static void main(String[] args) {
        Solution solution=new Solution();
        System.out.println(solution.generateMatrix(4));

    }
}
